<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class NavController extends Controller
{

   //前台显示导航
   public function nav(Request $request)
   {
       $nav = DB::table('nav')->get();
       return view('home.index',['nav'=>$nav,'request'=>$request]);
   }




    //后台导航添加
    public function getAdd()
    {   
         return view('admin.nav.add');
    }
 
    //导航显示
    public function getIndex(Request $request)
    {      
        //读取数据库
        $nav = DB::table('nav')->where(function($query) use($request){
                $k = $request->input('keyword');
                if(!empty($k)){
                    $query->where('title','like','%'.$k.'%');
                }
        })->paginate($request->input('num',10));
        return view('admin.nav.index',['nav'=>$nav,'request'=>$request]);
    }

    //导航添加
    public function postInsert(Request $request)
    {
      //进行表单验证
      $this->validate($request,[
        'title' => 'required',
        'description' => 'required',
        'link' => 'required',
        ],[
        'title.required' => '标题不能为空',
        'description.required' => '描述不能为空',
        'link.required' => '链接不能为空',
        ]);
      //获取数据
      $data = $request->except(['_token']);
      // dd($data);
      //插入数据库
      $res = DB::table('nav')->insert($data);
      // 检测
      if($res){
        return redirect('/nav/index')->with('info','添加成功 ');
      }else{
        return back()->with('error','添加失败');
      }
    }


     /**
     * 导航的修改页面
     */
    public function getEdit(Request $request)
    {
      //读取当前id的用户信息
      $id = $request->input('id');
      //读取数据库
      $nav = DB::table('nav')->where('id',$id)->first();
      //解析模板
      return  view('admin.nav.edit',['nav'=>$nav,'request'=>$request]);
    }
    /*
    *   执行修改
     */
     public function postUpdate(Request $request)
    {
      //进行表单验证
      $this->validate($request,[
        'title' => 'required',
        'description' => 'required',
        'link' => 'required',
        ],[
        'title.required' => '标题不能为空',
        'description.required' => '描述不能为空',
        'link.required' => '链接不能为空',
        ]);
      $data = $request->except(['_token','id']);
      //更新
      $res = DB::table('nav')->where('id',$request->input('id'))->update($data);
      if($res){
        return redirect('nav/index')->with('info','修改成功');
      }else{
        return back()->with('error','修改失败');
      }
    }

    /**
     * 导航删除操作
     */
    public function getDelete(Request $request)
    {
      $id = $request->input('id');
      //执行删除
      $res = DB::table('nav')->where('id',$id)->delete();
      if($res){
        return back()->with('info','删除成功');
      }else{
        return  back()->with('error','删除失败');
      }

    }




}
